<template>
    <div class="chatMain">

        <!-- 头部数据 -->
        <div class="chatMainHeader" v-if="isChat">
            <el-row>
                <el-col :span="12" style="text-align: left;font-weight: bold;font-size: 1.3rem;">
                    <a href="#">{{toUser.alias}}</a>
                </el-col>
                <el-col :span="12" style="text-align: right;">
                    <el-button icon="el-icon-s-platform"/>
                    <el-button icon="el-icon-coordinate"/>
                    <el-button icon="el-icon-folder"/>
                </el-col>
            </el-row>
        </div>
        <!-- 主要聊天区域数据 -->
        <div class="chatMainContent" v-if="isChat">
            <el-divider />
            <div id="msgContent">
                <template v-for="(item,index) in msgArray">
                    <el-row :key="index" v-if="item.receiveFlag===1" class="chatUserFrom">
                        <el-col :span="3">
                            <el-image
                                    class="chatUserImg"
                                    :src="item.img"
                            ></el-image>
                        </el-col>
                        <el-col :span="21" style="text-align: left" class="">
                            <div class="chatUserContentFrom">
                                {{ item.content }}
                            </div>
                        </el-col>
                    </el-row>

                    <el-row :key="index" v-if="item.receiveFlag===0" class="chatUserTo">
                        <el-col :span="21" style="text-align: right">
                            <span class="chatUserContentTo">
                                {{ item.content }}
                            </span>
                        </el-col>
                        <el-col :span="3" style="text-align: right">
                            <el-image
                                    class="chatUserImg"
                                    :src="item.img"
                            ></el-image>
                        </el-col>
                    </el-row>
                </template>
            </div>
        </div>

        <!-- 输入聊天数据 -->
        <div class="chatMainFooter" v-if="isChat">
            <el-divider style="margin: 5px 0px" />
            <el-input type="textarea" v-model="msgInput" @keyup.enter.native="sendMsg" style="font-size:20px;"/>
            <!--            <el-button type="primary" style="float: right" @click="sendMsg">发送消息</el-button>-->
        </div>

    </div>
</template>

<script>
    import * as $Constants from '../../api/Constants'

    export default {
        name: "chatMain",
        data() {
            return {
                msgArray: [],
                msgInput: '',
                isChat: false,
                toUser: {},     // 聊天用户
                fromUser: {}    // 当前用户
            }
        },
        mounted() {
            this.initPage();
            this.listenerNoReadMessage();
            this.listenTextMessage();
        },
        methods: {
            // 初始化页面
            initPage() {
                this.msgArray = [];
                this.msgInput = '';
                this.isChat = false;
                this.toUser = {};
                this.fromUser = {};
            },
            mainMsg() {

            },
            sendMsg() {
                if (this.msgInput === '' || this.msgInput.trim() === '') {
                    return;
                }
                let params = {};
                let msg = {};
                // 发送消息给服务端
                params.fromUser = this.fromUser.uid;
                params.toUser = this.toUser.uid;
                params.msgType = $Constants.MSG_TYPE_TEXT;
                params.content = this.msgInput;
                // TODO 如果websocket断开，需要进行重连处理
                let chatWebsocket = this.$store.state.chatWebsocket;
                chatWebsocket.send(JSON.stringify(params));

                // 本地展示处理
                // fromUser,toUser,readType,content,msgDate，receiveFlag，img
                msg.fromUser = this.fromUser.uid;
                msg.toUser = this.toUser.uid;
                msg.receiveFlag = $Constants.MSG_SEND_FLAG_SEND;
                msg.readType = $Constants.MSG_READ_TYPE_YES;
                msg.img = this.fromUser.img;
                msg.content = this.msgInput;
                msg.msgDate = new Date();
                this.msgArray.push(msg);

                // 储到vuex管理的消息管理中心
                this.$store.state.messageManager[msg.toUser].messages.push(msg);

                // 页面样式处理
                this.msgBottom();
                this.msgInput = '';
            },
            msgBottom() {
                setTimeout(function () {
                    let msgContent = document.getElementsByClassName('chatMainContent')[0];
                    msgContent.scrollTop = msgContent.scrollHeight;
                }, 100)
            },
            // 监听 leftUser组件传过来的事件noReadMessage
            listenerNoReadMessage() {
                let that = this;
                this.$root.Bus.$on('noReadMessage', (params, toUser) => {
                    this.msgInput = '';
                    this.msgArray = [];
                    this.isChat = true;
                    let userInfo = JSON.parse(window.localStorage.getItem('userInfo'));
                    this.fromUser = userInfo;
                    that.toUser = toUser;
                    for (let i = 0; i < params.length; i++) {
                        let msg = {};
                        for(let key in params[i] ){
                            msg[key] = params[i][key];
                        }
                        this.msgArray.push(msg);
                    }
                    // 处理消费信息
                    that.$store.state.messageManager[toUser.uid].msg_num = 0;
                    this.msgBottom();
                })
            },
            // 监听 index组件的文本消息信息
            listenTextMessage() {
                let that = this;
                this.$root.Bus.$on('textMessage', textMessage => {
                    /*
                    判断一下当前返回的消息实体是否和正在聊天的人相同
                    1.相同，则返回文本信息给聊天页面
                    2.不相同，则存储到全局的作用域中去
                     */
                    let msg = that.dealBackMessage(textMessage);
                    let uid = msg.fromUser;
                    let messages = that.$store.state.messageManager;
                    if (this.toUser.uid === undefined || uid !== this.toUser.uid) {
                        messages[uid].msg_num += 1;
                        // 需要设置leftUser未读数据图标个数
                        that.$root.Bus.$emit('sendMessage',msg);
                    } else {
                        that.msgArray.push(msg);
                        that.msgBottom();
                    }
                    messages[uid].messages.push(msg);
                })
            },
            // 处理后台返回的消息信息，返回前端展示的统一消息类型
            dealBackMessage(backMessage){
                // fromUser,toUser,readType,content,msgDate,receiveFlag(接收消息，发送消息),img(图片信息)
                let msg = {};
                msg.fromUser = backMessage.fromUser;
                msg.toUser = backMessage.toUser;
                msg.readType = $Constants.MSG_READ_TYPE_YES;
                msg.msgDate = new Date();
                msg.receiveFlag = $Constants.MSG_SEND_FLAG_RECEIVE;
                msg.img = this.$store.state.messageManager[backMessage.fromUser].friend.img;
                msg.content = backMessage.content;
                return msg;
            }
        }
    }
</script>

<style scoped>
    .chatMain {
        height: 100%;
        overflow: auto;
        background-color: #f5f6f7;
    }

    .chatMainHeader {
        height: 5%;
        padding: 1.2rem;
    }

    .chatMainContent {
        height: 75%;
        overflow: auto;
    }

    .chatMainFooter {
        padding-top: 1rem;
    }

    .chatUserImg {
        width: 40px;
        height: 40px;
    }

    .chatUserFrom {
        margin-top: 1rem;
    }

    .chatUserContentFrom {
        display: inline-block;
        font-size: 18px;
        background-color: #fbfbfb;
        color: #000000;
        padding: 1rem 2rem;
        border-radius: 10px;
    }

    .chatUserTo {
        margin-top: 1rem;
    }

    .chatUserContentTo {
        display: inline-block;
        font-size: 18px;
        background-color: #1e6eff;
        color: white;
        padding: 1rem 2rem;
        border-radius: 10px;
    }

    /** 覆盖原有的 el的分割线样式 */
    .el-divider--horizontal {
        display: block;
        height: 1px;
        width: 100%;
        margin: 10px 0;
    }

</style>
